package com.chuanyang.driverh.mainorder;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.amap.api.maps.model.LatLng;
import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.RecodeState;
import com.chuanyang.driverh.amap.MapUtils;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.mainorder.adapter.WayBillGoodInfoAdapter;
import com.chuanyang.driverh.mainorder.adapter.WayBillPassPointAdapter;
import com.chuanyang.driverh.mainother.BeforeNaviActivity;
import com.chuanyang.driverh.responseresult.CarCurrentStatusResult;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.OrderAddressResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.responseresult.ValidateCodeResult;
import com.chuanyang.driverh.responseresult.WayBillDetailResult;
import com.chuanyang.driverh.responseresult.WaybillDetailsData;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.TimeUtils;
import com.chuanyang.driverh.utils.eventbus.CloseWaybillDetailEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshOrderData;
import com.chuanyang.driverh.utils.eventbus.SubscribeEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.CustomMeasureHeightListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


public class WayBillDetailActivity extends BaseTitleActivity {
    private Dialog dialog;
    private ImageView iv_peopleicon;
    private RatingBar ratingBar;
    private TextView tv_peoplename;
    private TextView tv_phone;
    private TextView tv_deliverydate;
    private TextView tv_picuupdate;
    private TextView tv_waybillcode;
    private TextView tv_act;
    private CustomMeasureHeightListView lv_varpalaces;
    private CustomMeasureHeightListView lv_orderlist;
    private HashMap params;
    private ArrayList<WaybillDetailsData.PassPointsBean> passpointlist;
    public int index = 0;
    private ScrollView sc_waybilldetailinfo;
    private TextView tv_orderdate;
    private ArrayList<WaybillDetailsData.PassPointsBean> fillpointlist;
    private WaybillDetailsData.PassPointsBean startPoint;
    private WaybillDetailsData.PassPointsBean endPoint;
    private WayBillPassPointAdapter passPointAdapter;
    private WaybillDetailsData data;
    private LinearLayout ll_waybilldetail_div;
    private TextView tv_waybillinfo_dingyue;
    private LinearLayout ll_waybillinfo_act;
    private TextView tv_waybillinfo_act2;
    private TextView tv_waybillinfo_remark;
    private DriverInfoData driverinfo;
    private String waybillId;
    private TextView tv_waybillinfo_carshipdeliverydate;
    private TextView tv_waybillinfo_carshippicuupdate;
    private AlertDialog alertDialog;
    private EditText et_sureunload_code;
    private TextView tv_cancle_unload;
    private TextView tv_sureunload_getcode;
    private TextView tv_sure_unload;
    private boolean validateOk;
    private double   sumweight;
    private double   sumnum;
    private TextView tv_waybillinfodetail_count;
    private TextView tv_waybillinfodetail_load;
    private TextView tv_waybilldetail_amount;
    private TextView tv_waybilldetail_price;
    private double totalweight;
    private TextView tv_waybillinfodetail_tradetype;
    private TextView tv_waybillinfodetail_taskname;
    private LinearLayout ll_waybillinfodetail_account;
    private LinearLayout ll_waybillinfodetail_cartimediv;
    private TextView tv_waybillinfodetail_deliverydate;
    private TextView tv_waybillinfodetail_picuupdate;
    private LinearLayout ll_waybillinfodetail_shiptimediv;
    private TextView tv_waybillinfodetail_loaddatebeg;
    private TextView tv_waybillinfodetail_loaddateend;
    private TextView tv_waybillinfodetail_stevedoreDaybeg;
    private TextView tv_waybillinfodetail_stevedoreDayend;
    private TextView tv_waybillinfodetail_demurrage;
    private ImageView iv_dial;
    private ImageView iv_waybillinfo_phoneicon;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 1://确认
                    // updateWaybillUnload(data.getWaybillId());

                    break;
                case 2:
//                    SystemUtil.callTellphone(WayBillDetailActivity.this, data.getPhone());

                    break;
                case 3://确认收货
                    updateWaybillUnload();
                    break;
            }
        }
    };



    @Override
    protected int getContentResId() {
        return R.layout.order_act_waybilldetailinfo;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ll_waybilldetail_div = (LinearLayout) findViewById(R.id.ll_waybilldetail_div);
        sc_waybilldetailinfo = (ScrollView) findViewById(R.id.sc_waybilldetailinfo);
        iv_peopleicon = (ImageView) findViewById(R.id.iv_waybillinfo_peopleicon);
        ratingBar = (RatingBar) findViewById(R.id.rb_waybillinfo_stars);
        tv_peoplename = (TextView) findViewById(R.id.tv_waybillinfo_peoplename);
        tv_waybillinfo_remark = (TextView) findViewById(R.id.tv_waybillinfo_remark);
        tv_waybillinfo_dingyue = (TextView) findViewById(R.id.tv_waybillinfo_dingyue);//订阅
        tv_phone = (TextView) findViewById(R.id.tv_waybillinfo_phone);
        tv_waybillinfodetail_tradetype = (TextView) findViewById(R.id.tv_waybillinfodetail_tradetype);//订单外贸类型（1人民币，2美元）
        iv_dial = (ImageView) findViewById(R.id.iv_dial);
       iv_waybillinfo_phoneicon = (ImageView) findViewById(R.id.iv_dial);
        tv_waybillinfodetail_taskname = (TextView) findViewById(R.id.tv_waybillinfodetail_taskname);//任务名称有则显示 没有则不显示
        tv_orderdate = (TextView) findViewById(R.id.tv_waybillinfo_orderdate);//货单时间
        ll_waybillinfodetail_account = (LinearLayout) findViewById(R.id.ll_waybillinfodetail_account);
        tv_waybillcode = (TextView) findViewById(R.id.tv_waybillinfodetail_waybillid);//运单号
        //数量
        tv_waybillinfodetail_count = (TextView) findViewById(R.id.tv_waybillinfodetail_count);
        //载重
        tv_waybillinfodetail_load = (TextView) findViewById(R.id.tv_waybillinfodetail_load);
        //金额
        tv_waybilldetail_amount = (TextView) findViewById(R.id.tv_waybilldetail_amount);
        //单价
        tv_waybilldetail_price = (TextView) findViewById(R.id.tv_waybilldetail_price);

        //车辆运单时显示的界面
        ll_waybillinfodetail_cartimediv = (LinearLayout) findViewById(R.id.ll_waybillinfodetail_cartimediv);
        tv_waybillinfodetail_deliverydate = (TextView) findViewById(R.id.tv_waybillinfodetail_deliverydate);//发货时间
        tv_waybillinfodetail_picuupdate = (TextView) findViewById(R.id.tv_waybillinfodetail_picuupdate);//取货时间

        //-----------------------

        //船只运单时显示的界面
        ll_waybillinfodetail_shiptimediv = (LinearLayout) findViewById(R.id.ll_waybillinfodetail_shiptimediv);
        tv_waybillinfodetail_loaddatebeg = (TextView) findViewById(R.id.tv_waybillinfodetail_loaddatebeg);
        tv_waybillinfodetail_loaddateend = (TextView) findViewById(R.id.tv_waybillinfodetail_loaddateend);
        tv_waybillinfodetail_stevedoreDaybeg = (TextView) findViewById(R.id.tv_waybillinfodetail_stevedoreDaybeg);
        tv_waybillinfodetail_stevedoreDayend = (TextView) findViewById(R.id.tv_waybillinfodetail_stevedoreDayend);
        //滞期费
        tv_waybillinfodetail_demurrage = (TextView) findViewById(R.id.tv_waybillinfodetail_demurrage);

        //-----------------------


        tv_act = (TextView) findViewById(R.id.tv_waybillinfo_act);//最底部的按钮
        lv_varpalaces = (CustomMeasureHeightListView) findViewById(R.id.ll_waybillinfo_varpalace);
        lv_orderlist = (CustomMeasureHeightListView) findViewById(R.id.ll_waybillinfo_orderlist);
        ll_waybillinfo_act = (LinearLayout) findViewById(R.id.ll_waybillinfo_act);        //底部两个按钮所在布局
        tv_waybillinfo_act2 = (TextView) findViewById(R.id.tv_waybillinfo_act2);//底部的第二个按钮



    }

    @Override
    protected void initData() {
        RecodeState.setWayBillDetailOpenning(true);
        setBackImg();
        getTitleTextView().setText("运单详情");
        showActivityLoading();
        Intent intent = getIntent();
        driverinfo = BaseApplication.getInstance().getDriverInfo();
        waybillId = intent.getStringExtra("data");

        if (driverinfo.getDriver() != null && driverinfo.getDriver().getCarId() != 0) {
            GetCarCurrentStatusByCarID(driverinfo.getDriver().getCarId() + "");
        } else {
            GetCarCurrentStatusByCarID("");

        }

    }

    @Override
    protected void initListener() {
        tv_act.setOnClickListener(this);
        tv_waybillinfo_act2.setOnClickListener(this);
        ll_waybilldetail_div.setOnClickListener(this);
        iv_waybillinfo_phoneicon.setOnClickListener(this);

    }

    private void selectOrderAddress(String id) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", id);

        MyHttpUtil.selectOrderAddress(activityContext,params, new MyCallback<OrderAddressResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderAddressResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    Intent intent = new Intent(WayBillDetailActivity.this, BeforeNaviActivity.class);
                    intent.putExtra("OrderAddressResult", result);
                    startActivity(intent);
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }

    /**
     * 通过订单车辆位置
     * CarID
     *
     * @param
     */
    private void GetCarCurrentStatusByCarID(String carId) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("CarID", carId + "");

        MyHttpUtil.GetCarCurrentStatusByCarID(activityContext,params, new MyCallback<CarCurrentStatusResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                requsetData();
            }
            @Override
            public void onSuccess(CarCurrentStatusResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (result.getData() != null && result.getData().size() > 0) {
                        LatLng targetLatLng= MapUtils.getGdLatLng(WayBillDetailActivity.this,result.getData().get(0).getLast_lat() ,result.getData().get(0).getLast_lon());
                        SharedPrefUtil.setLongitude( targetLatLng.longitude+"");
                        SharedPrefUtil.setLatitude(targetLatLng.latitude+ "");
                    }
                }
                requsetData();
            }
        });

    }

    private void requsetData() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("waybillId", waybillId);
        MyHttpUtil.selectWaybillMsg(activityContext,params, new MyCallback<WayBillDetailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");

            }
            @Override
            public void onSuccess(WayBillDetailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    data = result.getData();
                    fillView(data);
                    hideActivityLoading();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_waybilldetail_div:
                if (data != null) {
                    startActivity(GoodOwnerInfoActivity.class, data);
                }
                break;
            case R.id.tv_waybillinfo_act:
                if (data.getWaybillStatus() == 2) {
                    if (data != null) {
                        startTranslate();
                    }

                } else if (data.getWaybillStatus() == 3) {
                    PrintUtil.toast(activityContext,"装货向导");

                } else if (data.getWaybillStatus() == 4) {
                    if (data != null) {
                        //  startActivity(MarkerActivity.class, data);
                        selectOrderAddress(data.getOrderId() + "");
                    }

                } else if (data.getWaybillStatus() == 5) {
                    PrintUtil.toast(activityContext,"卸货向导");

                } else if (data.getWaybillStatus() == 6) {
                    sureAcceptGood(handler);
                }
                break;

            case R.id.tv_waybillinfo_act2:
                if (data != null) {
                    Intent intent = new Intent(WayBillDetailActivity.this, SureUnLoadOverActivity.class);
                    intent.putExtra("waybillId", data.getWaybillId());
                    startActivity(intent);
                }
                break;
            case R.id.iv_dial:
                if (data.getPhone() != null) {
                    dial( data.getPhone());
//                    MyDialog.showTellDialog(this, handler, data.getPhone(), 2);
                }
                break;
        }
    }

    private void dial(final String tel){
        dialog= DialogUtil.myDialog(activityContext, "拨打电话", "取消", "确定","确定拨打："+tel+"?", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.dialog_btn_left:
                        break;
                    case R.id.dialog_btn_right:
                        DialogUtil.dial(activityContext,tel);
                       /* Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
                        try {
                            if (PermissoinUtil.checkAndRequestPermission(activityContext, android.Manifest.permission.CALL_PHONE, "请给应用添加拨打电话的权限！"))
                                startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }*/
                        break;
                }
                dialog.cancel();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideActivityLoading();
        RecodeState.setWayBillDetailOpenning(false);

    }

    /**
     * 修改运单状态
     */
    private void startTranslate() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", data.getWaybillId() + "");
        params.put("waybillStatus", "4");
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.startTranslate(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                        ll_waybillinfo_act.setVisibility(View.VISIBLE);
        //                    if (showUnload(endPoint.getLongitude(), endPoint.getLatitude())) {
                        if (data.getTransPortWay() == 1)//车
                        {
                            tv_act.setText("导航");

                        } else if (data.getTransPortWay() == 2) {
                            tv_act.setVisibility(View.GONE);
                        }
                        tv_waybillinfo_act2.setText("运输完成");
                        data.setWaybillStatus(4);
                        tv_waybillinfo_act2.setVisibility(View.VISIBLE);
                        EventBus.getDefault().post(new RefleshOrderData(2));

                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }


    /**
     * 提示司机输入收货人验证码
     *
     * @param mHandler
     */
    public void sureAcceptGood(final Handler mHandler) {
        if (null == alertDialog) {
            alertDialog = new AlertDialog.Builder(WayBillDetailActivity.this).create();
            alertDialog.show();
            alertDialog.setTitle(null);
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    alertDialog = null;
                }
            });
            Window window = alertDialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setBackgroundDrawable(new ColorDrawable(0));
            window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setContentView(R.layout.dialog_sureunload);
            View view = window.getDecorView();
            et_sureunload_code = (EditText) view.findViewById(R.id.et_sureunload_code);
            tv_cancle_unload = (TextView) view.findViewById(R.id.tv_cancle_unload);
            tv_sureunload_getcode = (TextView) view.findViewById(R.id.tv_sureunload_getcode);
            tv_sure_unload = (TextView) view.findViewById(R.id.tv_sure_unload);
            tv_cancle_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
            tv_sureunload_getcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!validateOk) {//获取成功验证码 且对话框没消失时无法多次点击
                        getValidateCode();
                    }
                    else {
                        PrintUtil.toast(activityContext,"验证码已发送给货主！");
                    }
                }
            });
            tv_sure_unload.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(et_sureunload_code.getText().toString().trim())) {
                        PrintUtil.toast(activityContext,"请填写获取到验证码");
                        return;
                    }
                    if (!validateOk){
                        PrintUtil.toast(activityContext,"请先获取验证码");
                        return;
                    }
                    mHandler.sendEmptyMessage(3);
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
        }
        //下面两行代码加入后即可弹出输入法
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    private void getValidateCode() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("phone", endPoint.getContactPhone());
        params.put("validateMsg", waybillId);
        MyHttpUtil.getSureValidateCode(activityContext,params, new MyCallback<ValidateCodeResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ValidateCodeResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                validateOk = true;
                tv_sureunload_getcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.tv_shape_gray_round_corner_solid));
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }

    /**
     * 收货完成 （传入订单id或者运单id）
     */
    private void updateWaybillUnload() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("waybillId", waybillId);
        params.put("waybillStatus", "7");
        params.put("validateMsg", waybillId);
        params.put("validateCode", et_sureunload_code.getText().toString().trim());
        MyHttpUtil.updateWaybillStatus(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(activityContext,"您已替货主确认收货");
                    EventBus.getDefault().post(new RefleshOrderData(2));
                    finish();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });

    }


    private void fillView(WaybillDetailsData data) {
        BitmapUtil.showImgForNetPath(data.getUserImage(),iv_peopleicon);
        ratingBar.setRating(data.getStar());
        tv_phone.setText(data.getPhone());
        tv_orderdate.setText(data.getCreatetime() + "");
        tv_waybillcode.setText(data.getWaybillNo());
        if(TextUtils.isEmpty(data.getAssignment()))
        {
            tv_waybillinfodetail_taskname.setVisibility(View.GONE);
        }
        else
        {
            tv_waybillinfodetail_taskname.setText("任务名称：    "+data.getAssignment());
        }
        if(data.getCurrency()==2)
        {
            tv_waybillinfodetail_tradetype.setVisibility(View.VISIBLE);
        }
        else {
            tv_waybillinfodetail_tradetype.setVisibility(View.GONE);

        }
        if (data.getTransPortWay() == 1)//车
        {
            tv_waybillinfodetail_deliverydate.setText(TimeUtils.getStandardTime(data.getOrder_startime()));
            tv_waybillinfodetail_picuupdate.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            ll_waybillinfodetail_cartimediv.setVisibility(View.VISIBLE);
            ll_waybillinfodetail_shiptimediv.setVisibility(View.GONE);

        } else if (data.getTransPortWay() == 2)//船
        {
            tv_waybillinfodetail_loaddatebeg.setText(data.getLoadDate());
            tv_waybillinfodetail_loaddateend.setText(TimeUtils.getStandardTime(data.getOrder_endtime()));
            tv_waybillinfodetail_stevedoreDayend.setText(data.getFq());

            tv_waybillinfodetail_stevedoreDaybeg.setText(data.getStevedoreDay());
            tv_waybillinfodetail_demurrage.setText(data.getDemurrage()+data.getUnit()+"/天/吨");
            ll_waybillinfodetail_cartimediv.setVisibility(View.GONE);
            ll_waybillinfodetail_shiptimediv.setVisibility(View.VISIBLE);

        }
        if (!TextUtils.isEmpty(data.getUsername())) {
            tv_peoplename.setText(data.getUsername());

        } else {
            tv_peoplename.setText("---");

        }
        if (!TextUtils.isEmpty(data.getRemark())) {
            tv_waybillinfo_remark.setText(data.getRemark());
        } else {
            tv_waybillinfo_remark.setText("");

        }
        if (data.getSubscriptionStatus() == 1) {
            tv_waybillinfo_dingyue.setText("已订阅");
        } else if (data.getSubscriptionStatus() == 2) {
            tv_waybillinfo_dingyue.setText("未订阅");
        }
        passpointlist = new ArrayList();
        //需要传入到适配器的数据
        fillpointlist = new ArrayList();
        passpointlist = new ArrayList();
        for (WaybillDetailsData.PassPointsBean passPointsBean : data.getPassPoints()) {
            if (passPointsBean.getPointType().equals("s")) {
                startPoint = passPointsBean;
            } else if (passPointsBean.getPointType().equals("p")) {
                passpointlist.add(passPointsBean);
            } else {
                endPoint = passPointsBean;

            }
        }
        WayBillGoodInfoAdapter orderInfoAdapter = new WayBillGoodInfoAdapter(this, data.getWaybillDetailMsgList());
        lv_orderlist.setAdapter(orderInfoAdapter);
        try{
            for(WaybillDetailsData.WaybillDetailMsgListBean   bean:data.getWaybillDetailMsgList())
            {
                double weight=Double.parseDouble(bean.getGoodsWeight());
                double num=Double.parseDouble(bean.getGoodsNum());
                sumweight=sumweight+weight;
                sumnum=sumnum+num;


            }
            tv_waybillinfodetail_load.setText(sumweight+"t");
            tv_waybillinfodetail_count.setText(sumnum+"");
            tv_waybilldetail_amount.setText("金额："+String.format("%.2f", sumweight*(data.getPrice()))+data.getUnit());
            tv_waybilldetail_price.setText("单价："+data.getPrice()+data.getUnit()+"/t");
        }catch (Exception e)
        {
            ll_waybillinfodetail_account.setVisibility(View.GONE);
        }


        fillpointlist.clear();
        fillpointlist.add(startPoint);
        lv_varpalaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (passpointlist.size() > 0) {
                    if (0 < position && position < passpointlist.size() + 1) {
                        fillpointlist.clear();
                        fillpointlist.add(startPoint);
                        if ((index++) % 2 == 1) {
                            fillpointlist.addAll(passpointlist);
                            fillpointlist.add(endPoint);

                        } else {
                            fillpointlist.add(passpointlist.get(0));
                            fillpointlist.add(endPoint);

                        }

                        passPointAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        if (passpointlist.size() > 0) {
            fillpointlist.add(passpointlist.get(0));

        }
        fillpointlist.add(endPoint);
        passPointAdapter = new WayBillPassPointAdapter(this, fillpointlist);
        //设置数据适配器
        lv_varpalaces.setAdapter(passPointAdapter);

        if (data.getWaybillStatus() < 0) {//运单全是个人的 且不存在状态1
            ll_waybillinfo_act.setVisibility(View.GONE);

        }
        if (data.getWaybillStatus() == 2) {
            tv_waybillinfo_act2.setVisibility(View.GONE);
            tv_act.setText("开始运输");

        } else if (data.getWaybillStatus() == 3) {
            tv_waybillinfo_act2.setVisibility(View.GONE);
            tv_act.setText("装货向导");


        } else if (data.getWaybillStatus() == 4) {
            // if (showUnload(endPoint.getLatitude(), endPoint.getLongitude())) {
            if (data.getTransPortWay() == 1) {
                tv_act.setText("导航");

            } else if (data.getTransPortWay() == 2) {
                tv_act.setVisibility(View.GONE);
            }
            tv_waybillinfo_act2.setText("运输完成");
//            } else {//如果当前时间不超过卸货时间半小时
//                tv_waybillinfo_act2.setVisibility(View.GONE);
//                tv_act.setText("导航");
//
//
//            }


        } else if (data.getWaybillStatus() == 5) {

            // if (showUnload(endPoint.getLatitude(), endPoint.getLongitude())) {
            tv_act.setText("卸货向导");
            tv_waybillinfo_act2.setText("运输完成");

//            } else {
//
//                tv_waybillinfo_act2.setVisibility(View.GONE);
//                tv_act.setText("卸货向导");


            //  }

        } else if (data.getWaybillStatus() == 6) {
            // ll_waybillinfo_act.setVisibility(View.GONE);
            tv_waybillinfo_act2.setVisibility(View.GONE);
            tv_act.setText("验证卸货");

        }
        else if(data.getWaybillStatus()==7)
        {
            ll_waybillinfo_act.setVisibility(View.GONE);
        }
        //滚动到原点  注意这两个方法需要一起使用 前者打断动画，后者实现移动
        sc_waybilldetailinfo.scrollTo(0, 0);
        sc_waybilldetailinfo.smoothScrollTo(0, 0);
    }




    public void onEventMainThread(SubscribeEvent event) {
        if (event.isChangeSubscribed()) {
            requsetData();
        }
    }

    /**
     * 关闭当前页面
     *
     * @param event
     */
    public void onEventMainThread(CloseWaybillDetailEvent event) {
        if (event.isFinish()) {
            finish();
        }

    }


}
